package com.demo.base.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description HTTP PUT请求 Helper
 * @date 2023/3/29 1:10 AM
 */
@Slf4j
public class HttpPutHelper {

    /** 请求配置 */
    private static RequestConfig requestConfig = null;

    private HttpPutHelper() {
        // 设置http的状态参数
        requestConfig =
                RequestConfig.custom()
                        .setSocketTimeout(5000)
                        .setConnectTimeout(5000)
                        .setConnectionRequestTimeout(5000)
                        .build();
        // TODO 补充其他配置
    }

    public static Boolean doAwsS3Put(String s3Url, String uploadImageUrl) {

        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        // 定义返回结果状态
        boolean result = false;

        try {
            // 创建http PUT请求
            HttpPut httpPut = new HttpPut(s3Url);
            httpPut.setConfig(requestConfig);

            // 设置请求头
            httpPut.addHeader("Content-Type", "text/plain");

            // 设置请求体
            URL url = new URL(uploadImageUrl);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            InputStreamEntity inputStreamEntity =
                    new InputStreamEntity(in, ContentType.APPLICATION_OCTET_STREAM);
            // 通过BufferedHttpEntity包装输入流，防止流被关闭
            BufferedHttpEntity bufEntity = new BufferedHttpEntity(inputStreamEntity);
            httpPut.setEntity(bufEntity);

            // 执行请求
            response = httpClient.execute(httpPut);

            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                log.info(
                        "HttpClient PUT请求成功，返回数据：{}",
                        EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));

                result = true;
            }
        } catch (Exception e) {
            log.error("HttpClient PUT请求发生异常，原因：{}", e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("HttpClient PUT请求关闭流失败，原因：{}", e.getMessage());
            }
        }

        return result;
    }
}
